package com.sunny;

import redis.clients.jedis.Jedis;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class LoginCookie {

    private static final String DEFAULT_IP = "222.201.145.179";
    private static final int DEFAULT_PORT = 5056;

    private Jedis conn;

    private ExecutorService tp = Executors.newSingleThreadExecutor();

    public LoginCookie(String ip, int port){
        conn = new Jedis(ip, port);
    }

    public LoginCookie() {
        conn = new Jedis(DEFAULT_IP, DEFAULT_PORT);
    }

    public String checkToken(String token){
        return conn.hget("token:", token);
    }

    public void updateToken(String token, String uid, int itemId){
        long timeStamp = System.currentTimeMillis();
        conn.hset("token:", token, uid);
        conn.zadd("recent:", timeStamp, token);
        if(0 != itemId){
            conn.zadd("viewed:"+token, timeStamp, String.valueOf(itemId));
            conn.zremrangeByRank("viewed:"+token, 0, -26);
        }
    }

    public void startCleanThread(){
        tp.submit(()->{
            System.out.println("开始清理");
            boolean quit = false;
            long limit = 1000;
            while (!quit){
               long size = conn.zcard("recent:");
               System.out.println("size="+size);
               if(size > limit){
                   try {
                       Thread.sleep(1000);
                       continue;
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
               }
               long lastIndex = size - limit;
               Set<String> tokens = conn.zrange("recent:",0, lastIndex-1);
               System.out.println("清理内存：" + tokens);
               tokens.forEach(token->{
                   conn.hdel("token:",token);
                   conn.zrem("recent:", token);
                   conn.del("viewed:"+token);
               });
            }
        });
    }

}
